package com.zlzlib.libindex.decoration;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zlz on 2019/10/31.
 * RecyclerView   LinearLayoutManager  带文字标题分割和悬浮头的Decoration
 */
public class TitleTextDecoration extends RecyclerView.ItemDecoration {

    private Context context;
    private List<TitleTextInterface> data;
    private Paint mPaint;
    private Rect mBounds;//用于存放测量文字Rect
    private int mTitleHeight;//title的高
    private int mTitleFontSize;//title字体大小
    //RecyclerView 头部有多少  要去除
    private int mHeaderViewCount = 0;
    //文字背景颜色
    private int titleBgColor = Color.parseColor("#FFDFDFDF");
    //文字颜色
    private int titleTextColor = Color.parseColor("#FF999999");
    private int mOrientation = LinearLayoutManager.VERTICAL;
    //竖直方向文字间隔
    private int vTextSpace = 10;


    public TitleTextDecoration(Context context) {
        this.data = new ArrayList<>();
        this.context = context;
        init();
    }

    private void init() {
        mPaint = new Paint();
        mBounds = new Rect();
        mTitleHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                30, context.getResources().getDisplayMetrics());
        mTitleFontSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                16, context.getResources().getDisplayMetrics());
        mPaint.setAntiAlias(true);
    }

    public TitleTextDecoration setData(List<? extends TitleTextInterface> data) {
        this.data.clear();
        this.data.addAll(data);
        return this;
    }

    public TitleTextDecoration setTitleHeight(int mTitleHeight) {
        this.mTitleHeight = mTitleHeight;
        return this;
    }

    public TitleTextDecoration setTitleFontSize(int mTitleFontSize) {
        this.mTitleFontSize = mTitleFontSize;
        return this;
    }

    public TitleTextDecoration setHeaderViewCount(int mHeaderViewCount) {
        this.mHeaderViewCount = mHeaderViewCount;
        return this;
    }

    public void setOrientation(int mOrientation) {
        this.mOrientation = mOrientation;
    }

    public void setTitleBgColor(int titleBgColor) {
        this.titleBgColor = titleBgColor;
    }

    public void setTitleTextColor(int titleTextColor) {
        this.titleTextColor = titleTextColor;
    }

    public int getHeaderViewCount() {
        return mHeaderViewCount;
    }

    //绘制分割的部分
    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);
        drawChildren(c, parent);
    }

    //绘制悬停的部分
    @Override
    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int position = ((LinearLayoutManager) (parent.getLayoutManager())).findFirstVisibleItemPosition();
        position -= getHeaderViewCount();
        if (data == null || data.isEmpty() || position > data.size() - 1 || position < 0 || !data.get(position).isShowTitle()) {
            return;
        }
        String title = data.get(position).getTitle();
        // View child = parent.getChildAt(pos);有时候child为空，
        // 所以将 child = parent.getChildAt(pos)。-》 parent.findViewHolderForLayoutPosition(pos).itemView
        View child = parent.findViewHolderForLayoutPosition(position + getHeaderViewCount()).itemView;
        if(child==null){
            return;
        }
        //定义一个flag，Canvas是否位移过的标志
        boolean flag = false;
        if (data.size() > position + 1) {
            //当前第一个可见的Item的tag，不等于其后一个item的tag，说明悬浮的View要切换了
            if (null != title && !title.equals(data.get(position + 1).getTitle())) {
                if (mOrientation == LinearLayoutManager.HORIZONTAL) {
                    //左右滑动的时候一样
                    int tran = child.getWidth() + child.getLeft();
                    if (child.getWidth() + child.getLeft() < mTitleHeight) {
                        c.save();//每次绘制前 保存当前Canvas状态，
                        flag = true;
                        //左滑时，将canvas左移 （x为负数） ,
                        c.translate(tran - mTitleHeight, 0);
                    }
                } else {
                    //当第一个可见的item在屏幕中还剩的高度小于title区域的高度时，我们也该开始做悬浮Title的“交换动画”
                    int tran = child.getHeight() + child.getTop();
                    if (tran < mTitleHeight) {
                        c.save();//每次绘制前 保存当前Canvas状态，
                        flag = true;
                        //上滑时，将canvas上移 （y为负数） ,所以后面canvas 画出来的Rect和Text都上移了，有种切换的“动画”感觉
                        c.translate(0, tran - mTitleHeight);
                    }
                }
            }
        }
        //绘制图像
        if (mOrientation == LinearLayoutManager.HORIZONTAL) {
            drawOverHTextBg(c, parent);
            if (null != title) {
                drawOverHText(c, child, parent, title);
            }
        } else {
            drawOverVTextBg(c, parent);
            if (null != title) {
                drawOverVText(c, child, parent, title);
            }
        }
        if (flag) c.restore();//恢复画布到之前保存的状态
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        position -= getHeaderViewCount();
        if (data == null || data.isEmpty() || position > data.size() - 1 || position < 0 || !data.get(position).isShowTitle()) {
            return;
        }
        String title = data.get(position).getTitle();
        if (position == 0) {
            if (mOrientation == LinearLayoutManager.HORIZONTAL) {
                outRect.set(mTitleHeight, 0, 0, 0);
            } else {
                outRect.set(0, mTitleHeight, 0, 0);
            }
        } else {
            if (null != title && !title.equals(data.get(position - 1).getTitle())) {
                if (mOrientation == LinearLayoutManager.HORIZONTAL) {
                    outRect.set(mTitleHeight, 0, 0, 0);
                } else {
                    outRect.set(0, mTitleHeight, 0, 0);
                }
            }
        }
    }

    //==============绘制分割的部分=====================
    private void drawChildren(Canvas c, RecyclerView parent) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int top = parent.getPaddingTop();
        int bottom = parent.getHeight() - parent.getPaddingBottom();
        mPaint.setTextSize(mTitleFontSize);
        for (int i = 0; i < parent.getChildCount(); i++) {
            //遍历 RecyclerView 的每个子view
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int position = params.getViewLayoutPosition();
            position -= getHeaderViewCount();
            //判断当前位置是否需要绘制图像
            if (data == null || data.isEmpty() || position > data.size() - 1 || position < 0 || !data.get(position).isShowTitle()) {
                continue;
            }
            String title = data.get(position).getTitle();
            if (position == 0) {
                //第一个肯定有
                drawTitleArea(c, left, right, top, bottom, child, params, title);
            } else {
                //不为空 且跟前一个title不一样了，说明是新的分类，也要title
                if (null != title && !title.equals(data.get(position - 1).getTitle())) {
                    drawTitleArea(c, left, right, top, bottom, child, params, title);
                }
            }
        }
    }

    private void drawTitleArea(Canvas c, int left, int right, int top, int bottom,
                               View child, RecyclerView.LayoutParams params, String title) {
        //背景最先调用，绘制在最下层
        if (mOrientation == LinearLayoutManager.HORIZONTAL) {
            drawHTextBg(c, top, bottom, child, params);
            drawHText(c, child, params, title);
        } else {
            drawVTextBg(c, left, right, child, params);
            drawVText(c, child, params, title);
        }
    }

    private void drawVTextBg(Canvas c, int left, int right, View child, RecyclerView.LayoutParams params) {
        mPaint.setColor(titleBgColor);
        int bottom = child.getTop() - params.topMargin;
        int top = bottom - mTitleHeight;
        c.drawRect(left, top, right, bottom, mPaint);
    }

    private void drawHTextBg(Canvas c, int top, int bottom, View child, RecyclerView.LayoutParams params) {
        mPaint.setColor(titleBgColor);
        int right = child.getLeft() - params.leftMargin;
        int left = right - mTitleHeight;
        c.drawRect(left, top, right, bottom, mPaint);
    }

    private void drawVText(Canvas c, View child, RecyclerView.LayoutParams params, String title) {
        //绘制横向文字
        mPaint.setColor(titleTextColor);
        mPaint.getTextBounds(title, 0, title.length(), mBounds);
        //文字起始点的y坐标
        int y = child.getTop() - params.topMargin - (mTitleHeight / 2 - mBounds.height() / 2);
        //x 坐标根据item的padding
        c.drawText(title, child.getPaddingLeft(), y, mPaint);
    }

    private void drawHText(Canvas c, View child, RecyclerView.LayoutParams params, String title) {
        //绘制纵向文字
        mPaint.setColor(titleTextColor);
        //从上到下一个一个的绘制
        char[] text = title.toCharArray();
        int count = text.length;
        int indexY = child.getPaddingTop();
        for (int i = 0; i < count; i++) {
            //计算文字 大小
            mPaint.getTextBounds(text, i, 1, mBounds);
            if (i == 0) {
                indexY += mBounds.height() / 2;
            }
            //计算每个的 x, y
            int x = child.getLeft() - (mTitleHeight / 2 + mBounds.width() / 2);
            //文字起始点的y坐标
            int y = indexY += mBounds.height() + vTextSpace;
            c.drawText(text, i, 1, x, y, mPaint);
        }
    }

    //=================绘制悬浮的=======================
    private void drawOverVTextBg(Canvas c, RecyclerView parent) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int top = parent.getPaddingTop();
        int bottom = top + mTitleHeight;
        mPaint.setColor(titleBgColor);
        c.drawRect(left, top, right, bottom, mPaint);
    }

    private void drawOverHTextBg(Canvas c, RecyclerView parent) {
        int left = parent.getPaddingLeft();
        int right = left + mTitleHeight;
        int top = parent.getPaddingTop();
        int bottom = parent.getHeight() - parent.getPaddingBottom();
        mPaint.setColor(titleBgColor);
        c.drawRect(left, top, right, bottom, mPaint);
    }

    private void drawOverVText(Canvas c, View child, RecyclerView parent, String title) {
        mPaint.setColor(titleTextColor);
        mPaint.getTextBounds(title, 0, title.length(), mBounds);
        int y = parent.getPaddingTop() + mTitleHeight - (mTitleHeight / 2 - mBounds.height() / 2);
        c.drawText(title, child.getPaddingLeft(), y, mPaint);
    }

    private void drawOverHText(Canvas c, View child, RecyclerView parent, String title) {
        //绘制纵向文字
        mPaint.setColor(titleTextColor);
        //从上到下一个一个的绘制
        char[] text = title.toCharArray();
        int count = text.length;
        int indexY = child.getPaddingTop();
        for (int i = 0; i < count; i++) {
            //计算文字 大小
            mPaint.getTextBounds(text, i, 1, mBounds);
            if (i == 0) {
                indexY += mBounds.height() / 3;
            }
            //计算每个的 x, y
            int x = parent.getPaddingLeft() + (mTitleHeight / 2 - mBounds.width() / 2);
            //文字起始点的y坐标
            int y = indexY += mBounds.height() + vTextSpace;
            c.drawText(text, i, 1, x, y, mPaint);
        }
    }
}
